import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_device_id/flutter_device_id.dart';
import 'package:flutter_yn_goods/utils/http/http_export.dart';
import 'package:flutter_yn_goods/utils/shared/shared_export.dart';

// import 'package:flutter_yn_goods/utils/shared/shared_export.dart';
import 'package:flutter_keychain/flutter_keychain.dart';

import 'package:package_info_plus/package_info_plus.dart';
import 'package:uuid/uuid.dart';
import 'package:flutter_yn_goods/pages/model/model_app_config.dart';
import 'package:get/get.dart';

class AppConfig {
  static String baseUrl = "https://app.betterforever.info/";
  static bool isProductionEnv = false;

  static String appName = '';
  static String version = '';
  static String channelId = '1';
  static String currentDeviceId = "";
  static int serviceDifference = 0;
  static ModelAppConfig? appConfig;

  static Future setup() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();

    setAppName();
    version = packageInfo.version;

    await initDeviceId();
  }

  static void setAppName() {
    final locale = Get.locale ?? const Locale('en', 'US');
    final languageCode = locale.languageCode;
    
    switch(languageCode) {
      case 'zh':
        appName = '良久';
        break;
      case 'vi':
        appName = 'Mãi tốt hơn';
        break;
      case 'en':
      default:
        appName = 'better forever';
        break;
    }
  }

  static getAppConfig() async {
    HttpResponse response = await HttpManager()
        .get(API.getAppConfig, fromJson: ModelAppConfig.fromJson);
    if (response.isSuccess) {
      AppConfig.appConfig = response.data;
    }
  }

  static initDeviceId() async {
    // SharedKey
    String deviceId = SharedStorage().getDeviceId() ?? "";
    if (deviceId.isEmpty) {
      deviceId = await FlutterKeychain.get(key: SharedKey.deviceId) ?? "";
      if (Platform.isAndroid && "9774d56d682e549c" == deviceId) {
        deviceId = "";
      }
      if (deviceId.isEmpty) {
        deviceId = (await FlutterDeviceId().getDeviceId()) ?? '';
        if (deviceId.isEmpty) {
          deviceId = const Uuid().v4();
          FlutterKeychain.put(key: SharedKey.deviceId, value: deviceId);
        }
      }
    }
    currentDeviceId = deviceId;
  }
}
